package com.fyales.android.api.http;

import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.telephony.TelephonyManager;

import com.fyales.android.api.constant.HttpConstants;
import com.fyales.android.util.DevUtil;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import okio.Buffer;


/**
 * @author fyales
 * @since 15/11/9.
 * 网络请求拦截器
 */
public class RestRequestInterceptor implements Interceptor {

    Config config;

    public RestRequestInterceptor(Config config) {
        this.config = config;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request requset = chain.request();

        if ("GET".equals(requset.method())) {
            requset = addGetPublicKeyValue(requset);
        } else if ("POST".equals(requset.method())) {
            requset = addPostPublicKeyValue(requset);
        }

        return chain.proceed(requset);
    }


    /**
     * 添加Get方法的键值对
     *
     * @return Request
     */
    private Request addGetPublicKeyValue(Request request) {
        String url = request.urlString();
        String[] urlTemp = url.split("\\?");
        HashMap<String, String> map = new HashMap<>();
        if (urlTemp.length > 1) {
            String[] params = urlTemp[1].split("&");

            for (int i = 0; i < params.length; i++) {
                String[] keyValue = params[i].split("=");
                map.put(keyValue[0], keyValue[1]);
            }
        }
        addCommonKeyValue(map);
        //重新塑造URL
        String urlParams = "";
        for (Map.Entry entry : map.entrySet()) {
            urlParams += "&" + entry.getKey() + "=" + entry.getValue();
        }
        urlParams = urlParams.substring(1);
        url = urlTemp[0] + "?" + urlParams;

        DevUtil.v("Retrofit","URL is " + url);         //打印URL

        return request.newBuilder()
                .url(url)
                .build();
    }

    /**
     * 临时方法，将HashMap转换为TreeMap
     * @param map
     * @return
     */
    private TreeMap<String, String> hashMapToTreeMap(HashMap<String, String> map) {
        TreeMap<String, String> params = new TreeMap<>(new Comparator<Object>() {
            public int compare(Object o1, Object o2) {
                if (o1 == null || o2 == null) {
                    return 0;
                } else {
                    return String.valueOf(o1).compareTo(String.valueOf(o2));
                }
            }
        }
        );

        for (Map.Entry entry : map.entrySet()) {
            params.put(entry.getKey().toString(), entry.getValue().toString());
        }

        return params;
    }


    /**
     * 增加POST方法的键值对
     *
     * @return Request
     */
    private Request addPostPublicKeyValue(Request request) {
        String queryParams = bodyToString(request);
        HashMap<String, String> map = new HashMap<>();

        if (request.body() != null) {
            String[] params = queryParams.split("&");
            for (int i = 0; i < params.length; i++) {
                String[] keyValue = params[i].split("=");
                map.put(keyValue[0], keyValue[1]);
            }
        }
        addCommonKeyValue(map);
        queryParams = "";
        //重新塑造RequestBody
        for (Map.Entry entry : map.entrySet()) {
            queryParams += "&" + entry.getKey() + "=" + entry.getValue();
        }
        queryParams = queryParams.substring(1);

        DevUtil.v("Retrofit","Url is " + request.urlString());
        DevUtil.v("Retrofit","The params is " + map.toString());
        //重新塑造request
        return request.newBuilder()
                .post(RequestBody.create(request.body().contentType(), queryParams.getBytes()))
                .build();
    }


    /**
     * 增加通用的公共参数
     *
     * @param map
     */
    private void addCommonKeyValue(HashMap<String, String> map) {
        map.put("key", HttpConstants.APP_KEY);
    }


    /**
     * 当请求方式是POST的时候得到字段里面的键值对
     *
     * @param request
     * @return
     */
    private String bodyToString(Request request) {
        Buffer buffer = new Buffer();
        try {
            request.body().writeTo(buffer);
            return buffer.readUtf8();
        } catch (IOException e) {
            return "did not work";
        }
    }


    /**
     * 得到签名哈希
     *
     * @return
     */
    private int getSignHash() {
        try {
            Context context = config.getApplication();
            Signature[] sigs = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES).signatures;
            if (null != sigs && sigs.length > 0) {
                return sigs[0].hashCode();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


}
